package com.networkmmc.demo.data;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.networkmmc.demo.sql.SqlObj;

import java.util.ArrayList;
import java.util.List;

/**
 * 转换SQL工具类
 */
public class ConvertToSql {

    /**
     * ListData 转换为 Insert SQL
     * @param dl
     */
    public static List<SqlObj> toSql(List<List<Object>> dl, String tableName, String[] fields, int[] maxNums){
        List<SqlObj> sqlList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dl) && dl.size() > 0){
            SqlObj sqlObj;
            for (List<Object> list : dl) {
                int j = 0;
                sqlObj = new SqlObj(tableName);
//                sqlObj.addFields(fields[j], IdUtil.fastSimpleUUID());
                for (Object o: list) {
                    if(ObjectUtil.isNotEmpty(o)) {
                        if(ObjectUtil.isNotEmpty(maxNums) && ObjectUtil.isNotEmpty(maxNums[j]) && NumberUtil.parseInt(StrUtil.toString(maxNums[j])) < StrUtil.length(o.toString())){
                            sqlList = new ArrayList<>();
                            System.out.println(StrUtil.format("字段{}长度为{}，数据长度为{}，请修改字段长度后再试！", fields[j], maxNums[j], StrUtil.length(o.toString())));
                            return sqlList;
                        }
                        sqlObj.addFields(fields[j], o);
                    }
                    j++;
                }
                sqlList.add(sqlObj);
            }
        }
        return sqlList;
    }

    public static List<String> modifyColSql(List<List<Object>> dl, String tableName, String[] fields, int[] maxNums, String[] fieldNames){
        List<String> sqlList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dl) && dl.size() > 0){
            SqlObj sqlObj;
            for (List<Object> list : dl) {
                int j = 0;
                sqlObj = new SqlObj(tableName);
                sqlObj.addFields(fields[j], IdUtil.fastSimpleUUID());
                for (Object o: list) {
                    if(ObjectUtil.isNotEmpty(o)) {
                        if(ObjectUtil.isNotEmpty(maxNums) && ObjectUtil.isNotEmpty(maxNums[j]) && NumberUtil.parseInt(StrUtil.toString(maxNums[j])) < StrUtil.length(o.toString())){
                            System.out.println(StrUtil.format("字段{}长度为{}，数据长度为{}", fields[j], maxNums[j], StrUtil.length(o.toString())));
                            maxNums[j] = StrUtil.length(o.toString());
                            sqlList.add("ALTER TABLE `" + tableName + "` MODIFY COLUMN `" + fields[j] + "` VARCHAR(" + StrUtil.length(o.toString()) + ") COMMENT '" + fieldNames[j] + "'");
                        }
                        sqlObj.addFields(fields[j], o);
                    }
                    j++;
                }
            }
        }
        return sqlList;
    }
}
